package com.wang.elm.security;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wang.elm.dao.UserMapper;
import com.wang.elm.dao.UserPermissionMapper;
import com.wang.elm.dao.UserRoleMapper;
import com.wang.elm.entity.User;
import com.wang.elm.entity.UserPermission;
import com.wang.elm.entity.UserRole;
import jakarta.annotation.Resource;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class MyUserDetailsService implements UserDetailsService {

    /*
     *  UserDetailsService：提供查询用户功能，如根据用户名查询用户，并返回UserDetails
     *UserDetails，SpringSecurity定义的类， 记录用户信息，如用户名、密码、权限等
     * */
    @Resource
    private UserMapper sysUserMapper;

    @Resource
    private UserRoleMapper userRoleMapper;
    @Resource
    private UserPermissionMapper userPermissionMapper;
    @Resource
    private JwtTokenUtil jwtTokenUtil;

    @Override
    public UserDetails loadUserByUsername(String userId) throws UsernameNotFoundException {

            //根据用户名从数据库中查询用户
        System.out.println("自定义登录服务-loadUserName方法执行");
        User  sysUser = sysUserMapper.selectById(userId);
        if (sysUser==null){
            System.out.println("用户名不存在"+userId+"不存在");
            throw new UsernameNotFoundException("用户不存在");
        }
//        org.springframework.security.core.userdetails.User result =
//                new org.springframework.security.core.userdetails.User(
//                        userId,
//                        sysUser.getPassword(),
//                        AuthorityUtils.NO_AUTHORITIES
//                );
//        return result;
        QueryWrapper<UserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        List<UserRole> userRoles = userRoleMapper.selectList(queryWrapper);


        List<String> userRoleIds = userRoles.stream()
                .map(UserRole::getId) // 或者 UserRole::getUserRoleId，取决于UserRole的实际属性名
                .collect(Collectors.toList());

        List<UserPermission> userPermissions = userRoleIds.stream()
                .flatMap(userRoleId -> {
                    QueryWrapper<UserPermission> queryWrapper1 = new QueryWrapper<>();
                    queryWrapper1.eq("role_id", userRoleId);
                    return userPermissionMapper.selectList(queryWrapper1).stream();
                })
                .collect(Collectors.toList());
// 封装用户信息和权限


        List<String> authorities = new ArrayList<>();
        for (UserRole role: userRoles) {
            //角色名称纳入的权限管理，必须增加前缀 ROLE_
            authorities.add("ROLE_"+role.getRoleName());
        }
        for (UserPermission permission : userPermissions){
            authorities.add(permission.getPermissionName());
        }
//        sysUser.setToken(jwtTokenUtil.generateToken(sysUser.getUserId()));
        CustomUserDetails customUserDetails = new CustomUserDetails(
                sysUser,
                AuthorityUtils.createAuthorityList(authorities) // 或者您可以添加实际的权限
        );


        return customUserDetails;


    }
}

